import os
import re

def process_root_directories():
    """处理当前根目录下的所有文件夹（无论是否包含子目录）"""
    print("Processing root directories...")
    changed = False
    for entry in os.listdir():
        entry_path = os.path.join(os.getcwd(), entry)
        if entry.startswith('.'):  # 跳过隐藏文件/目录
            print(f"Skipping hidden: {entry}")
            continue
        if os.path.isdir(entry_path):  # 仅处理目录
            # 先去掉最后一个 .pdf 后的内容（不区分大小写）
            temp_name = re.sub(r'(\.pdf).*', r'\1', entry, flags=re.IGNORECASE)
            # 再替换Windows非法字符、逗号、常见OCR脏字符（如方括号、+、中文引号）为下划线
            new_name = re.sub(r'[<>:\"\/\\|?*,，\[\]\(\)\+“”]', '_', temp_name)
            if new_name != entry:
                try:
                    os.rename(entry, new_name)
                    print(f"Renamed: {entry} → {new_name}")
                    changed = True
                except OSError as e:
                    print(f"Error renaming {entry}: {e}")
            else:
                print(f"No change needed: {entry}")
        else:
            print(f"Skipping non-directory: {entry}")
    if not changed:
        print("No directories needed modification.")

def main():
    process_root_directories()
    print("处理完成，窗口将自动关闭。")

if __name__ == "__main__":
    main()